package cn.afactory.tygz.ui.base.utils.sns;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.View;
import android.widget.TextView;

import com.lidroid.xutils.util.LogUtils;

import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.afactory.tygz.model.SnsCommentInfo;

public class HealthCircleTextUtil {
    public static String getLocString(Context ctx,String mLocDetail){
//        if(mLocDetail == null ) return ctx.getString(R.string.loc_string);
//        return !TextUtils.isEmpty(mLocDetail) ? mLocDetail : ctx.getString(R.string.loc_string);
        return "";
    }

    public static String getReplyInfo(Context ctx,SnsCommentInfo mInfo) {
//        if (mInfo == null || mInfo.replyToUserId <= 0){
//            return ctx.getString(R.string.square_send_msg_hint);
//        }
//
//        try {
//            return ctx.getString(R.string.health_subject_reply)
//                    + mInfo.replyToUserInfo.nick
//                    + ctx.getString(R.string.health_subject_reply_suffix);
//        } catch (Exception e){
//            e.printStackTrace();
//            return ctx.getString(R.string.square_send_msg_hint);
//        }
        return "";
    }

    // 直接拷贝这些代码到你希望的位置，然后在TextView设置了文本之后调用就ok了
    public static void SetLinkClickIntercept(Context ctx, TextView tv, final TextUtilListener mItemClickListener) {
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        CharSequence text = tv.getText();
        if (text instanceof Spannable) {
            int end = text.length();
            Spannable sp = (Spannable) tv.getText();
            SpannableStringBuilder spannable = new SpannableStringBuilder(text);

            URLSpan[] urls = sp.getSpans(0, end, URLSpan.class);
            if (urls.length == 0) {
                spannable = highlightKeyword(ctx, text.toString(),spannable,mItemClickListener);
                tv.setText(spannable);
                return;
            }

            // 只拦截 http:// URI
            LinkedList<String> myurls = new LinkedList<String>();
            for (URLSpan uri : urls) {
                String uriString = uri.getURL();
                if (uriString.indexOf("http://") == 0 || uriString.indexOf("https://") == 0) {
                    myurls.add(uriString);
                }
            }
            //循环把链接发过去
            for (URLSpan uri : urls) {
                String uriString = uri.getURL();
                if (uriString.indexOf("http://") == 0 || uriString.indexOf("https://") == 0) {
                    MyURLSpan myURLSpan = new MyURLSpan(ctx, uriString, myurls);
                    spannable.setSpan(myURLSpan, sp.getSpanStart(uri),
                            sp.getSpanEnd(uri), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                }
            }

            spannable = highlightKeyword(ctx, text.toString(), spannable,mItemClickListener);
            tv.setText(spannable);
        }
    }

    /**
     * 处理TextView中的链接点击事件
     * 链接的类型包括：url，号码，email，地图
     * 这里只拦截url，即 http:// 开头的URI
     */
    private static class MyURLSpan extends ClickableSpan {
        private String mUrl;                    // 当前点击的实际链接
        private LinkedList<String> mUrls; // 根据需求，一个TextView中存在多个link的话，这个和我求有关，可已删除掉
        private final Context mContext;

        // 无论点击哪个都必须知道该TextView中的所有link，因此添加改变量
        MyURLSpan(Context ctx, String url, LinkedList<String> urls) {
            mUrl = url;
            mUrls = urls;
            mContext = ctx;
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View widget) {
            // 这里你可以做任何你想要的处理
            // 比如在你自己的应用中用webview打开，而不是打开系统的浏览器
            String info = new String();
            if (mUrls.size() == 1) {
                // 只有一个url，根据策略弹出提示对话框
                info = mUrls.get(0);
            }
            else {
                // 多个url，弹出选择对话框，意思一下
                info = mUrls.get(0) + "\n" + mUrls.get(1);
            }
//            Toast.makeText(context, info, Toast.LENGTH_SHORT).show();
//            Uri uri = Uri.parse(mUrl);
//            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//            context.startActivity(intent);
//            NavigationUtils.gotoWebBrowser(mContext, mUrl, null, false);
        }
    }

    /** 设置话题高亮和点击
     * @param str
     * @param mItemClickListener
     */
    public static SpannableStringBuilder highlightKeyword(Context ctx, String str, SpannableStringBuilder sp,final TextUtilListener mItemClickListener) {

//        SpannableString sp = new SpannableString(str);

        Pattern p = Pattern.compile("([#])\\w+([#])");
        Matcher m = p.matcher(str);

        while (m.find()) {  //通过正则查找，逐个高亮
            int start = m.start();
            int end = m.end();
            sp.setSpan(new LinkSpan(ctx, m.group(),mItemClickListener), start ,end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
//        tv.setText(sp);
        return sp;
    }

    /**  确定是否只含有话题
     * @param str
     * @return
     */
    public static boolean onlyHasTopic(String str){
        if(str == null) {
            return false;
        }

        Pattern p = Pattern.compile("([#])\\w+([#])");
        Matcher m = p.matcher(str);

        while (m.find()) {  //通过正则查找，逐个高亮
            int start = m.start();
            int end = m.end();
            str = str.replace(str.substring(start, end),"");
            m = p.matcher(str);
            LogUtils.e("loza start:" + start + " end:" + end + "str: " + str);
        }

        LogUtils.e("loza str: " + str + " trim:" + str.trim() + "length:" + str.trim().length());
//        m = p.matcher(str);
//        m.find() && m.start() == 0 && m.end() == (str.length());
        return str.trim().length() <= 0;
    }



    private static class LinkSpan extends ClickableSpan {
        private final Context mContext;
        private String mLink;
        private final TextUtilListener listener;
        LinkSpan(Context ctx, String url, TextUtilListener mItemClickListener) {
            mLink = url;
            mContext = ctx;
            listener = mItemClickListener;
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View widget) {
            listener.onClickSubjectList(mLink);
        }
    }
}
